<?php
/**
 * Created by PhpStorm.
 * User: lengbin
 * Date: 2018/10/11
 * Time: 下午7:18
 */

namespace common\core\actions;

use common\core\base\Action;
use common\helpers\Html;

/**
 * delete
 *
 * Class DeleteAction
 * @package common\core\actions
 */
class DeleteAction extends Action
{
    /**
     * request param by get
     *
     * @var string
     */
    public $modelByParam = 'id';

    /**
     * request param by post
     *
     * @var string
     */
    public $modelByParams = 'selection';


    /**
     *  call_user_func
     * @var string
     */
    public $delete;

    /**
     * delete filed name
     *
     * @var string
     */
    public $isDeleteName = 'is_delete';



    public function run()
    {
        // request  post / get  params
        if (\Yii::$app->request->isPost) {
            $id = \Yii::$app->request->post($this->modelByParams);
        } else {
            $id = \Yii::$app->request->get($this->modelByParam);
        }

        try {
            if ($this->delete instanceof \Closure) {
                $row = call_user_func($this->delete, $id);
            } else {
                if (is_array($id)) {
                    $row = $this->modelClass->deleteByIds($id, $this->isDeleteName);
                } else {
                    $row = $this->modelClass->deleteById($id, $this->isDeleteName);
                }
            }
            if ($row) {
                $this->successAlert('删除成功');
            } else {
                $this->errorAlert('删除失败');
            }
        } catch (\Exception $exception) {
            $str = str_replace(PHP_EOL, '', Html::encode($exception->getMessage()));
            $this->errorAlert($str);
        }

        return $this->redirect();
    }
}